<template>
  <div class="box">
    <div class="title">Promise学习</div>
    <div v-for="item in person" :key="item.name">{{ item }}</div>
  </div>
  <div class="box">
    <div class="title">树型数据扁平化</div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { city_data } from '@/utils/test_data'
onMounted(() => {
  test()
  APItest()
})

/**
 * 1.使用map和Pormise.all实现并行请求
 */
const test = () => {
  const arr = [1, 2, 3, 4, 5]
  //   使用map配合Pormise.all实现并行请求
  //   当有需求要求将获取的接口数据中，根据返回的某个参数再遍历接口数据，可以使用map和Pormise.all实现并行请求
  const promiseList = arr.map(item => {
    return new Promise((resolve, reject) => {
      // 使用定时器模拟接口异步请求
      setTimeout(() => {
        console.log(item)
        resolve()
      }, 2000)
    })
  })
  console.log(promiseList, 'promiseList>>>>>>')
  Promise.all(promiseList).then(() => {
    console.log('ss')
  })
}
const person = ref({
  name: '张三',
  age: 18
})
const API1 = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let obj1 = [
        {
          name: '张三',
          age: 18
        },
        {
          name: '里斯',
          age: 33
        },
        {
          name: '李四',
          age: 22
        },
        {
          name: '王五',
          age: 25
        }
      ]
      resolve(obj1)
    }, 2000)
  })
}
const API2 = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let obj2 = [
        {
          address: '深圳'
        },
        {
          address: '北京'
        },
        {
          address: '上海'
        },
        {
          address: '广州'
        }
      ]
      resolve(obj2)
    }, 2000)
  })
}
// const APItest = () => {
//   let data
//   API1().then(res => {
//     data = res
//     console.log(res)
//   })
//   console.log(data, 'data>>>>>>>>>>')
// }
const APItest = async () => {
  let data = await API1()
  const promiseList = data.map((item, index) => {
    return API2().then(res => {
      return (item.address = res[index].address)
    })
  })
  Promise.all(promiseList).then(res => {
    console.log(res, 'res>>>>>>>>>>')
    console.log(data, 'data>>>>>>>>>>')
    person.value = data
  })
}

/**
 * 将树形数据进行扁平化
 */
const treeData = ref(city_data)
const treeToFlatList = data => {
  let flatList = []
  data.forEach(item => {
    flatList.push(item)
    if (item.gisDataTreeDTOList.length !== 0) {
      flatList.push(...treeToFlatList(item.gisDataTreeDTOList))
    }
  })
  console.log(flatList, 'flatList>>>>>>>>>>')
  return flatList
}
onMounted(() => {
  console.log(treeData.value, 'treeData.value>>>>>>>>>>')
  treeData.value = treeToFlatList(treeData.value)
  console.log(treeData.value, 'treeData.value>>>>>>>>>>')
})
</script>
<style lang="scss" scoped>
.box {
  margin-bottom: 20px;
}
.title {
  margin-left: 20px;
  font-size: 20px;
  font-weight: 500;
}
</style>
